/**
 * @description: 数据中台-权限管理-租户管理-用户管理-新建/修改用户
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import IceContainer from '@icedesign/container';
import {Button, Input, Message, Select, Upload} from '@alifd/next';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import styles from './index.module.scss';
import responsive from '@/request'
import $http from '@/service/Services';

const axios = $http;

const {Option} = Select;
let form;


/**
 * list
 */
class UserEditComponents extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileId: "",
            userType: props.user, //user admin
            value: {},
            roleList: [],
            id: "",
            orgId: "",
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const id = this.props.id;
        const orgId = this.props.orgId;
        this.setState({
                id: id,
                orgId: orgId
            }
            , () => {
                
            }
        );

        if (id) {
            const that = this;
            axios.post(responsive.responsive.url + '/v1/user/findUserById',{
                userId:id
            })
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        const d = data.data;
                        // d["roleId"] = d.roleInstances[0].role.id;
                        that.setState({
                            fileId: data.data.logo,
                            value: data.data
                        })
                    }
                })
                .catch(function (error) {
                    console.error(error);
                    Message.error(error.message);
                })
        }
    };

    /* 表改变
    * @param formValue
    */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };

    /**
     * 验证密码
     * @param rule
     * @param values
     * @param callback
     */
    checkPasswd = (rule, values, callback) => {
        if (!values) {
            callback('请输入正确的密码');
        } else if (values.length < 8) {
            callback('密码必须大于8位');
        } else if (values.length > 16) {
            callback('密码必须小于16位');
        } else {
            callback();
        }
    };
    /**
     * 验证密码
     * @param rule
     * @param values
     * @param callback
     * @param stateValues
     */
    checkPasswd2 = (rule, values, callback, stateValues) => {
        if (!values) {
            callback('请输入正确的密码');
        } else if (values && values !== stateValues.passwd) {
            callback('两次输入密码不一致');
        } else {
            callback();
        }
    };
    /**
     * 表验证
     */
    validateAllFormField = () => {
        form.validateAll((errors, values) => {
            if (errors) {
                const err = errors.some(
                    o => {
                        return o.message
                    }
                );
                if (err) {
                    Message.warning('请填写必要的数据.');
                    return;
                }

            }
            if (!this.state.id) {
                const password = values.password;
                const repassword = values.rePassword;
                if (password !== repassword) {
                    Message.warning('两次密码不相同.');
                    return null;
                }
            }
            const that = this;
            values["orgId"] = this.state.orgId;
            values["logo"] = this.state.fileId;
            axios.post(responsive.responsive.url + '/v1/user/addOrUpdateUser', values)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data.name);
                    } else {
                        Message.success("操作成功.");
                        that.props.history.go(-1);
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        });
    };
    /**
     *
     * @param file  {Object} 文件
     * @param value {Array} 值
     */
    onSuccess = (file, value) => {
        const dataList = file.response.data;
        let fileId = dataList[0].fileId;
        this.setState(
            {
                fileId: fileId
            }
        )
    };

    /**
     *
     * @param file  {Object} 出错的文件
     * @param fileList  {Array} 当前值
     */
    onError = (file, fileList) => {
        console.log('Exceed limit', file, fileList);
    };

    /**
     * 手机号码验证
     */
    checkCode = (rule, values, callback) => {
        if (!(/^1[3456789]\d{9}$/.test(values))) {
            callback('手机号码有误');
        } else if (values.length > 0 && values.length < 11) {
            callback('手机号码由11位数字组成');
        } else if (values.length == 0) {
            callback('手机号码不能为空');
        } else {
            callback("");
        }
    };

    /**
     * 表
     * @returns {*}
     */
    render() {
        const actionUrl = responsive.responsive.url + '/v1/file/upload';
        const {fileId} = this.state;
        const fileUrl = responsive.responsive.url + '/v1/file/download/' + fileId;
        return (
            <div>
                <div className='container-header'>
                    <p style={{display: 'inline-block'}}>{this.state.id ? "修改用户" : "新建用户"}</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return'
                            style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }}> 返回</a>
                    </Button>
                </div>


                <IceContainer className='container-main'>
                    <IceFormBinderWrapper
                        value={this.state.value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formContent}>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}></div>
                                <div className={styles.imagesDiv}>
                                    {
                                        [1].map(
                                            o => {
                                                return fileId ?
                                                    (<img src={fileUrl} className={styles.textCenter} alt={""}/>)
                                                    :
                                                    (<object className={styles.textCenter}
                                                             data={require("./images/header.svg")} type="image/svg+xml"
                                                             codebase="http://www.adobe.com/svg/viewer/install/"/>)
                                            }
                                        )
                                    }
                                    <div className={styles.uploadText}>
                                        <Upload
                                            headers={
                                                {
                                                    'Authorization': sessionStorage.getItem("Authorization")
                                                }
                                            }
                                            action={actionUrl}
                                            limit={1}
                                            accept={"image/*"}
                                            listType="text"
                                            onSuccess={this.onSuccess = this.onSuccess.bind(this)}
                                            onError={this.onError = this.onError.bind(this)}>
                                            <Button type="primary" style={{margin: '0 0 10px'}}>上传</Button>
                                        </Upload>
                                    </div>
                                </div>
                            </div>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 用户昵称：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 用户名称不能为空"
                                    name="name"
                                >
                                    <Input maxLength={10}
                                           placeholder="请输入用户名称"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="name"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 登录用户名：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message="登录用户名不能为空"
                                    name="account"
                                >
                                    <Input maxLength={10}
                                           placeholder="请输入登录用户名"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="loginName"/>
                                </div>
                            </div>


                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 邮箱：</div>
                                <IceFormBinder
                                    required
                                    type="email"
                                    triggerType="onBlur"
                                    message=" 邮箱不能为空"
                                    name="email"
                                >
                                    <Input maxLength={20}
                                           placeholder="请输入邮箱"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="email"/>
                                </div>
                            </div>


                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 手机号码：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    // message=" 手机号码不能为空"
                                    name="phone"
                                    validator={this.checkCode}
                                >
                                    <Input maxLength={11}
                                           placeholder="请输入手机号码"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="phone"/>
                                </div>
                            </div>

                            {
                                [1].map(o => {
                                    return this.state.id ? (<div>&nbsp;</div>) : (
                                        <div>
                                            <div className={styles.formItem}>
                                                <div className={styles.formLabel}><span
                                                    style={{color: '#FF3000'}}>*</span> 密码：
                                                </div>
                                                <IceFormBinder
                                                    required
                                                    triggerType="onBlur"
                                                    message=" 密码不能为空"
                                                    name="password"
                                                >
                                                    <Input maxLength={30}
                                                           placeholder="请输入密码"
                                                           htmlType="password"
                                                           className={styles.inputNme}
                                                    />
                                                </IceFormBinder>
                                                <div className={styles.formError}>
                                                    <IceFormError name="password"/>
                                                </div>
                                            </div>


                                            <div className={styles.formItem}>
                                                <div className={styles.formLabel}><span
                                                    style={{color: '#FF3000'}}>*</span> 确认密码：
                                                </div>
                                                <IceFormBinder
                                                    required
                                                    triggerType="onBlur"
                                                    message=" 确认密码不能为空"
                                                    name="rePassword"

                                                >
                                                    <Input maxLength={30}
                                                           placeholder="请输入确认密码"
                                                           htmlType="password"
                                                           className={styles.inputNme}
                                                    />
                                                </IceFormBinder>
                                                <div className={styles.formError}>
                                                    <IceFormError name="rePassword"/>
                                                </div>
                                            </div>
                                        </div>
                                    )
                                })
                            }

                            {/*<div className={styles.formItem}>*/}
                            {/*    <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 角色：</div>*/}
                            {/*    <IceFormBinder*/}
                            {/*        required*/}
                            {/*        triggerType="onBlur"*/}
                            {/*        message=" 角色不能为空"*/}
                            {/*        name="roleId"*/}
                            {/*    >*/}
                            {/*        <Select*/}
                            {/*            placeholder="请选择"*/}
                            {/*            className={styles.inputNme}*/}
                            {/*        >*/}
                            {/*            {*/}
                            {/*                this.state.roleList.map(*/}
                            {/*                    o => {*/}
                            {/*                        return (<Option value={o.id}>{o.name}</Option>)*/}
                            {/*                    }*/}
                            {/*                )*/}
                            {/*            }*/}
                            {/*        </Select>*/}
                            {/*    </IceFormBinder>*/}
                            {/*    <div className={styles.formError}>*/}
                            {/*        <IceFormError name="roleId"/>*/}
                            {/*    </div>*/}
                            {/*</div>*/}
                            <Button
                                type="primary"
                                className='pipe-btn-submit'
                                onClick={this.validateAllFormField}
                            >
                                提 交
                            </Button>
                        </div>
                    </IceFormBinderWrapper>
                </IceContainer>
            </div>
        );
    }

}

export default UserEditComponents;
